﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace ADayRoiAdmin
{
    public partial class frmProducts : Form
    {
        int productid = 0;
        static SqlConnection con = null;
        private string temp_picThumb = string.Empty, temp_picSummary = String.Empty;
        AdayroiClass adayroi = new AdayroiClass(ref con);
        DataTable dt_prices = null;
        private Boolean deleted = false;
        DataRow dr_product = null;
        private BindingSource binding = new BindingSource();
        public frmProducts(int productid,DataRow dr_product)
        {
            InitializeComponent();
            this.productid = productid;
            this.dr_product = dr_product;
        }

        private void frmProducts_Load(object sender, EventArgs e)
        {
            DataTable dt_category = adayroi.getList("select * from Category where Parent = 0 and IsDisplay = 'TRUE' order by Sort ", con);
            cbCategoryID.DataSource = dt_category;
            cbCategoryID.DisplayMember = "Name";
            cbCategoryID.ValueMember = "PKID";

            if (productid > 0)
            {
                btnThem.Visible = false;
                dr_product = adayroi.getList("select p.*, c.Parent from Products p left join Category c on p.CategoryID = c.PKID where p.PKID = " + productid, con).Rows[0];
                cbCategoryID.SelectedValue = dr_product["Parent"].ToString();
                cbCategoryID2.SelectedValue = dr_product["CategoryID"].ToString();
                txtProductName.Text = dr_product["ProductName"].ToString();
                txtProductCode.Text = dr_product["ProductCode"].ToString();
                txtDescription.Text = dr_product["Description"].ToString();
                txtDoUuTien.Text = dr_product["Sort"].ToString();
                chkhienthi.Checked = (bool)dr_product["isDisplay"];

                if (dr_product["Image"].ToString() != String.Empty)
                    adayroi.lay_hinh
                        ("/Code/Upload/Products/" + dr_product["Image"].ToString(), picSummary);

                if (dr_product["ImageThumbnail"].ToString() != String.Empty)
                    adayroi.lay_hinh
                        ("/Code/Upload/Products/Thumb/" + dr_product["ImageThumbnail"].ToString(), picThumb);
            }
            else btnCapNhat.Visible = false;       
            //san pham

            dt_prices = adayroi.getList("select PKID,ProductID,PriceActual,PricePromotion,SinceDate from Prices where ProductID = " + productid, con);
            dgv_PriceLoad();
            binding.DataSource = dt_prices;
            dgvPrice.DataSource = binding;
       
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            if (adayroi.ftp_picture(temp_picThumb, "/Code/Upload/Products/Thumb/" + Path.GetFileName(temp_picThumb)) == 0)
            {
                if (adayroi.ftp_picture(temp_picSummary, "/Code/Upload/Products/" + Path.GetFileName(temp_picSummary)) == 0)
                {

                    string businessid = "0";
                    if (cbBusinessID.Items.Count != 0) businessid = cbBusinessID.SelectedValue.ToString();
                    string sql = "insert into Products (ProductCode,ProductName,CategoryID,BusinessID,ImageThumbnail,Image,Description,IsDisplay,Sort,CreatedOn) values (N'"
                        + txtProductCode.Text + "',N'"
                        + txtProductName.Text + "',"
                        + cbCategoryID2.SelectedValue + ","
                        + businessid + ",'" +
                        Path.GetFileName(temp_picThumb) + "','" +
                        Path.GetFileName(temp_picSummary) + "',N'" + txtDescription.Text + "','" + chkhienthi.Checked + "','" + txtDoUuTien.Text + "','" + DateTime.Now.ToString() + "')";
                    UpdateReload(sql, businessid);
                    this.Close();
                    
                }
                else
                {
                    MessageBox.Show("Upload Hình bị lỗi, vui lòng thử lại một lần nữa");
                }
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {

            string businessid = "0";
            if (cbBusinessID.Items.Count != 0) businessid = cbBusinessID.SelectedValue.ToString();
            if (!String.IsNullOrEmpty(temp_picThumb) && Path.GetFileName(temp_picThumb) != dr_product["ImageThumbnail"].ToString())
                adayroi.deleteFile("ftp://buyall.vn/httpdocs", "/Code/Upload/Products/Thumb/", dr_product["ImageThumbnail"].ToString());

            if (!String.IsNullOrEmpty(temp_picSummary) && Path.GetFileName(temp_picSummary) != dr_product["Image"].ToString())
                adayroi.deleteFile("ftp://buyall.vn/httpdocs", "/Code/Upload/Products/", dr_product["Image"].ToString());

            if (adayroi.ftp_picture(temp_picThumb, "/Code/Upload/Products/Thumb/" + Path.GetFileName(temp_picThumb)) == 0)
            {
                if (adayroi.ftp_picture(temp_picSummary, "/Code/Upload/Products/" + Path.GetFileName(temp_picSummary)) == 0)
                {
                    string str_picThumb = Path.GetFileName(temp_picThumb);
                    string str_picSummary = Path.GetFileName(temp_picSummary);
                    if (str_picThumb == "") str_picThumb = dr_product["ImageThumbnail"].ToString();
                    if (str_picSummary == "") str_picSummary = dr_product["Image"].ToString();
                    string sql = "Update Products set Image = '" + str_picSummary
                        + "', ImageThumbnail = '" + str_picThumb
                        + "', ProductCode = N'" + txtProductCode.Text 
                        + "', ProductName = N'" + txtProductName.Text 
                        + "',Description = N'" + txtDescription.Text 
                        + "', CategoryID = " + cbCategoryID2.SelectedValue
                        + ", BusinessID = " + businessid 
                        + ", IsDisplay = '" + chkhienthi.Checked
                        + "', Sort = " + txtDoUuTien.Text 
                        + ", UpdatedOn = '" + DateTime.Now 
                        + "' where PKID = " + dr_product["PKID"].ToString();
                    if (UpdateReload(sql, businessid) == 0)
                    {
                        if (update_price() == 0)
                            MessageBox.Show("Thành Công");
                    }
                }
            }
            else
            {
                MessageBox.Show("Upload Hình bị lỗi, vui lòng thử lại một lần nữa");
            }

        }

        private int UpdateReload(string sql, string businessid)
        {
           
            if (txtDoUuTien.Text == "") txtDoUuTien.Text = "0";
            string str_picThumb = Path.GetFileName(temp_picThumb);
            string str_picSummary = Path.GetFileName(temp_picSummary);
            if (str_picThumb == "") str_picThumb = dr_product["ImageThumbnail"].ToString();
            if (str_picSummary == "") str_picSummary = dr_product["Image"].ToString();

            dr_product["ProductCode"] = txtProductCode.Text;
            dr_product["ProductName"] = txtProductName.Text;
            dr_product["Description"] = txtDescription.Text;
            dr_product["Image"] = str_picSummary;
            dr_product["ImageThumbnail"] = str_picThumb;
            dr_product["CategoryID"] = cbCategoryID2.SelectedValue;
            dr_product["BusinessID"] = businessid;
            dr_product["IsDisplay"] = chkhienthi.Checked;
            dr_product["Sort"] = Convert.ToInt32(txtDoUuTien.Text);
            return adayroi.UpdateSQL(con, sql);

        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult response = MessageBox.Show("Bạn có chắc chắn muốn xóa?", "Xóa dòng?", MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button2);
            if (response == DialogResult.Yes)
            {
                adayroi.deleteFile("ftp://buyall.vn/httpdocs", "/Code/Upload/Products/Thumb/", dr_product["ImageThumbnail"].ToString());
                adayroi.deleteFile("ftp://buyall.vn/httpdocs", "/Code/Upload/Products/", dr_product["Image"].ToString());
                string sql = "delete from Products where PKID = " + productid;
                if (adayroi.UpdateSQL(con, sql) == 0)
                    MessageBox.Show("Thành Công");
                deleted = true;
            }
            else return;
        }

        public bool _deletedrow
        {
            get { return deleted; }
        }

        private void picThumb_Click(object sender, EventArgs e)
        {
            string picture = adayroi.get_path_pic();
            temp_picThumb = adayroi.loadpicture(picture, picThumb);
        }

        private void txtDoUuTien_KeyPress(object sender, KeyPressEventArgs e)
        {
            adayroi.key_press(sender, e);
        }

        private void picSummary_Click(object sender, EventArgs e)
        {
            string picture = adayroi.get_path_pic();
            temp_picSummary = adayroi.loadpicture(picture, picSummary);
        }

        private void cbCategoryID_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable dt_category2 = adayroi.getList("select * from Category where Parent = "+cbCategoryID.SelectedValue.ToString()+" and IsDisplay = 'TRUE' order by Sort ", con);
                cbCategoryID2.DataSource = dt_category2;
                cbCategoryID2.DisplayMember = "Name";
                cbCategoryID2.ValueMember = "PKID";
            }
            catch { }
        }

        private void cbCategoryID2_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable dt_category3 = adayroi.getList("select * from Business where CategoryID = " + cbCategoryID2.SelectedValue.ToString() + " and IsDisplay = 'TRUE' order by Sort ", con);
                cbBusinessID.DataSource = dt_category3;
                cbBusinessID.DisplayMember = "Name";
                cbBusinessID.ValueMember = "Business_ID";
                
            }
            catch { }
        }

        public DataRow _dr_product
        {
            get { return dr_product; }
        }

        private void dgv_PriceLoad()
        {
            DataGridViewTextBoxColumn PKID = new DataGridViewTextBoxColumn();
            PKID.DataPropertyName = "PKID";
            PKID.Name = "PKID";
            PKID.Visible = false;

            DataGridViewTextBoxColumn PriceActual = new DataGridViewTextBoxColumn();
            PriceActual.DataPropertyName = "PriceActual";
            PriceActual.Name = "PriceActual";
            PriceActual.HeaderText = "Giá gốc";

            DataGridViewTextBoxColumn PricePromotion = new DataGridViewTextBoxColumn();
            PricePromotion.DataPropertyName = "PricePromotion";
            PricePromotion.HeaderText = "Gía còn lại";
            PricePromotion.Name = "PricePromotion";

            DataGridViewTextBoxColumn ProductID = new DataGridViewTextBoxColumn();
            ProductID.DataPropertyName = "ProductID";
            ProductID.Name = "ProductID";
            ProductID.Visible = false;

            DataGridViewTextBoxColumn SinceDate = new DataGridViewTextBoxColumn();
            SinceDate.DataPropertyName = "SinceDate";
            SinceDate.Name = "SinceDate";
            SinceDate.HeaderText = "Ngày Bắt Đầu";
            SinceDate.Visible = false;

            dgvPrice.Columns.AddRange(new DataGridViewColumn[] { PKID,PriceActual,PricePromotion,SinceDate,ProductID });
        }

        private int update_price()
        {          
            int maloi = 0;
            dt_prices = (DataTable)binding.DataSource;
            foreach (DataRow dr in dt_prices.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                {
                    int pkid = (int)dr["PKID", DataRowVersion.Original];
                    maloi = adayroi.UpdateSQL(con, " delete Prices where PKID = " + pkid);
                }
                else
                if (dr.RowState==DataRowState.Modified)
                {
                    maloi = adayroi.UpdateSQL(con, " update Prices set PriceActual = " + dr["PriceActual"].ToString() + ", PricePromotion = " +
                        dr["PricePromotion"].ToString() + ", SinceDate = '" + dr["SinceDate"].ToString() + "' where PKID = " + dr["PKID"].ToString());

                }
                else if(dr.RowState==DataRowState.Added)
                {
                    maloi = adayroi.UpdateSQL(con, " insert into Prices (PriceActual,PricePromotion,ProductID,SinceDate) values (" + dr["PriceActual"].ToString() +
                        ", " + dr["PricePromotion"].ToString() + "," + productid + ", '" + dr["SinceDate"].ToString() + "')");
                }
                    
            }
            dt_prices = adayroi.getList("select PKID,ProductID,PriceActual,PricePromotion,SinceDate from Prices where ProductID = " + productid, con);
            dgv_PriceLoad();
            binding.DataSource = dt_prices;
            dgvPrice.DataSource = binding;
            return maloi;
        }

        private void dgvPrice_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int colcurrent = this.dgvPrice.CurrentCell.ColumnIndex;
            string colheader = dgvPrice.Columns[colcurrent].Name;
           
               if (e.Control is TextBox)
                {
                    TextBox tb = e.Control as TextBox;
                    tb.KeyPress += new KeyPressEventHandler(adayroi.key_press);
                }
         
        }

        private void chkhienthi_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void btn_Image_Click(object sender, EventArgs e)
        {
            fmImages fmImages2 = new fmImages(productid, "ProductID");
            fmImages2.ShowDialog();
        }

    }
}
